<template>
    <div ref="canvasContainer" class="canvas-container">
      <canvas ref="canvas" class="canvas"></canvas>
    </div>
</template>

<script setup lang="ts">
import {onMounted, onUnmounted, ref} from 'vue';
import {invoke} from "@tauri-apps/api/core";
import {getCurrentWindow} from "@tauri-apps/api/window";
import {emit} from "@tauri-apps/api/event";


const canvas = ref(null);
const canvasContainer = ref(null);
const ctx = ref(null);
const isMouseDown = ref(false);
const startX = ref(0);
const startY = ref(0);
const width = ref(0);
const height = ref(0);

onMounted(() => {
  const canvasEl = canvas.value;
  ctx.value = canvasEl.getContext('2d');

  // 设置 canvas 大小
  canvasEl.width = window.innerWidth;
  canvasEl.height = window.innerHeight;
  ctx.value.fillStyle = "rgba(0, 0, 0, 0.5)";
  ctx.value.fillRect(0, 0, canvasEl.width, canvasEl.height );
  // 监听鼠标事件
  canvasEl.addEventListener('mousedown', handleMouseDown);
  canvasEl.addEventListener('mousemove', handleMouseMove);
  canvasEl.addEventListener('mouseup', handleMouseUp);
});

onUnmounted(() => {
  // 移除鼠标事件监听器
  canvas.value.removeEventListener('mousedown', handleMouseDown);
  canvas.value.removeEventListener('mousemove', handleMouseMove);
  canvas.value.removeEventListener('mouseup', handleMouseUp);
});

const handleMouseDown = (event) => {
  isMouseDown.value = true;
  startX.value = event.clientX;
  startY.value = event.clientY;
  width.value = 0;
  height.value = 0;
};

const handleMouseMove = (event) => {
  if (isMouseDown.value) {
    width.value = event.clientX - startX.value;
    height.value = event.clientY - startY.value;
    drawRectangle();
  }
};

const  handleMouseUp =  ()=> {
  isMouseDown.value = false;
  console.log(`Selected Rectangle: StartX=${startX.value}, StartY=${startY.value}, Width=${width.value}, Height=${height.value}`);
  invoke("screenshot", {x: startX.value, y: startY.value, width: width.value, height: height.value}).then(async  (data) => {
    await emit('send-message-other-window',data);
    await getCurrentWindow().close();
  })
};

const drawRectangle = () => {
  // 画矩形
  ctx.value.globalCompositeOperation = 'destination-out';
  ctx.value.fillStyle = "rgba(255,255,255, 1)";
  ctx.value.fillRect(startX.value, startY.value, width.value, height.value);
  ctx.globalCompositeOperation = 'source-over';
};


</script>
<style>
html,body ,#app {
  background: none !important;
}
</style>
<style scoped>

.canvas-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.canvas {
  position: absolute;
  top: 0;
  left: 0;
  cursor: crosshair;
}
</style>
